package cn.tedu.socket;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    private Socket socket;
    public Client() {
        try {
            System.out.println("正在连接服务器");
            socket = new Socket("localhost", 8088);
            System.out.println("与服务器端建立了连接");
        } catch (IOException e) {
            System.out.println("出现异常");
        }
    }
    public void start(){
        try {
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out,"UTF-8");
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw,true);

            InputStream in = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(in,"UTF-8");
            BufferedReader br = new BufferedReader(isr);


            Scanner scan = new Scanner(System.in);
            while (true){
                String line = scan.nextLine();
                if ("exit".equalsIgnoreCase(line)){
                    break;
                }
                pw.println(line);
                line = br.readLine();
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("捕获写出的字节通过网络发送给对方的异常.");
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                System.out.println("关闭socket流连接");
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }
}
